<template>
	<view class="page">
		<!-- 订单状态筛选 -->
		<view class="order-status">
			<view class="status-item cursor-pointer" @click="tabChange(index)" :class="tabIndex==index?'active':''"
				v-for="(item,index) in tabList" :key="index">
				{{item}}
				<!-- <view class="dot"></view> -->
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y @scrolltolower="loadMore">
			<view class="order-card"  v-for="item in orders" @click="toDetail(item)">
				<view class="card-header">
					<view class="hotel-name">sn: {{ item.sn }}</view>
					<view class="order-state" v-if="item.pay_status == 0 && item.refund_status != 1">待支付</view>
					<view class="order-state" v-if="item.pay_status == 1 && item.refund_status != 1">已支付</view>
					<view class="order-state" v-if="item.pay_status == 2 && item.refund_status != 1">已取消</view>
					<view class="order-state" v-if="item.refund_status == 1">已退款</view>
				</view>
				<!-- <view class="card-info">
					<uni-icons type="calendar" size="16" />
					<text class="info-text">{{ getDateTimeMonthDay(item.start_time) }} 至 {{ getDateTimeMonthDay(item.end_time) }} 住1晚</text>
				</view> -->
				<view class="room-price-row">
					<!-- <view class="room-info">
						<uni-icons type="home" size="16" />
						<text class="info-text">{{ item.roomInfo.name }}，{{ item.number }}间</text>
					</view> -->
					<view class="price">
						<text class="currency">¥</text>
						<text class="amount">{{ item.order_amount }}</text>
					</view>
				</view>
				<view class="divider"></view>
				<view class="card-actions flex-row justify-end">
					<view class="btn-cancel flex-row justify-center items-center cursor-pointer" v-if="item.pay_status == 0" @click.stop="cancelOrderFun(item.id)">取消订单</view>
					<view class="btn-pay flex-row justify-center items-center cursor-pointer" v-if="item.pay_status == 0" @click.stop="payOrder(item)">支付押金</view>
					<view class="btn-pay flex-row justify-center items-center cursor-pointer" v-if="item.is_disable_refund == 1 && item.refund_status == 0" @click.stop="depositRefund(item.id)">申请退款</view>
				</view>
			</view>
			<view v-if="orders.length == 0">
				<!-- <image  class="none" src="../../static/none.png" mode=""></image> -->
				<view class="none">暂无数据</view>
			</view>
		</scroll-view>
	</view>
</template>

<script lang="ts" setup>
	// import myTaber from "@/components/myTaber.vue"
	import { ref, computed, toRaw } from 'vue';
	import {
		onShow,
		onLoad
	} from "@dcloudio/uni-app";
	import { getDateTimeMonthDay } from '@/utils/time.js'
	import { deposit_orderCancel, deposit_orderList, payRefund_deposit, payDeposit } from '@/utils/apiPost.js'
	import WechatSDK from '@/utils/wechat_sdk.js'
	import wx from 'weixin-js-sdk';
	const currentCategory = ref('hotel'); // 当前分类
	const currentStatus = ref('all'); // 当前状态
	const currentTab = ref('order'); // 当前底部导航选项
	const tabIndex = ref(0); // 当前导航栏
	const tabList = ref(['全部', '待支付', '已支付']); // 当前导航栏

	// --- Pagination State ---
	const pageNo = ref(1);          // 当前页码 (page number)
	const pageSize = ref(10);         // 每页项目数 (根据需要调整)
	const loading = ref(false);       // 指示加载是否正在进行的 flag
	const finished = ref(false);      // 指示是否已加载所有数据的 flag
	const loadingText = ref('加载中...'); // 加载期间/结束时显示的文本

	// 示例订单数据
	interface orderListItem {
		sn: string,
		id: number,
		order_amount: string,
		pay_status: number,
		refund_status: number,
		is_disable_refund: number
	}
	const orders = ref<orderListItem[]>([]);
	orders.value = [
		// {
		//   id: 1,
		//   hotelName: '庭酒店（杭州阿里店）',
		//   checkInDate: '03/01',
		//   checkOutDate: '03/02',
		//   nights: 1,
		//   roomType: '纯享单人间',
		//   price: 245.00,
		//   status: '待支付'
		// },
		// {
		//   id: 2,
		//   hotelName: '杭州西湖四季酒店',
		//   checkInDate: '03/05',
		//   checkOutDate: '03/06',
		//   nights: 1,
		//   roomType: '豪华双人间',
		//   price: 1288.00,
		//   status: '待入住'
		// }
	]
	
	
	// 过滤订单
	const filteredOrders = computed(() => {
		return orders.value.filter(order => {
			if (currentStatus.value === 'all') return true;
			return order.status === currentStatus.value;
		});
	});

	const toDetail = (item) => {
		// let obj = toRaw(item)
		uni.navigateTo({
			url: `/pages/order-detail/order-detail?id=${item.id}`
		})
	};
	// 切换状态
	const switchStatus = (status) => {
		currentStatus.value = status;
	};

	// 处理取消订单
	const onCancelOrder = (orderId) => {
		console.log('取消订单:', orderId);
	};

	// 处理支付订单
	const onPayOrder = (orderId) => {
		console.log('支付订单:', orderId);
	};

	// 刷新订单列表
	const onRefresh = () => {
		console.log('刷新订单列表');
	};

	// 加载更多订单
	const onLoadMore = () => {
		console.log('加载更多订单');
	};

	// 导航到其他页面
	const navigateTo = (page) => {
		console.log('导航到:', page);
	};
	// const getDeposit_orderListFun = () => {
	// 	let obj = {
	// 		page_no: 1,
	// 	}
	// 	deposit_orderList().then(res=>{
	// 		console.log(res)
	// 		if(res.code == 1){
	// 			orders.value = res.data.list
	// 		}
	// 	}).catch(error=>{
	// 		console.log(error)
	// 	})
	// }
	const totalNum = ref(0)
	const getDeposit_orderListFun = async (isLoadMore = false) => {
		console.log(isLoadMore, loading.value)
		// 防止在已经在加载（loading）或已完成（finished）时重复获取（除非是刷新操作）
		if (!isLoadMore && loading.value) return; // 如果已经在 loading，不要刷新
		if (isLoadMore && (loading.value || finished.value)) {
		    console.log('已经在 loading 或 finished，跳过 load more。');
		    return; // 如果已经在 loading 或 finished，不要加载更多
		}
			
		loading.value = true; // 设置 loading state
		loadingText.value = '加载中...'; // 重置加载文本
			
		// 如果不是加载更多（即，是刷新或初始加载），则重置 state
		if (!isLoadMore) {
			pageNo.value = 1;
			finished.value = false;
			orders.value = []; // 清空现有列表以进行全新加载
		}
		let obj = {
			page_no: pageNo.value,
			type: tabIndex.value
		}
		console.log("使用参数请求订单列表:", obj);
		
		try {
			const res = await deposit_orderList(obj);
			console.log("API Response:", res);
			
			if (res.code == 1 && res.data) {
		        const newData = (res.data.list || []) as orderListItem[]; // 确保它是一个 array
				totalNum.value = res.data.total
				if (pageNo.value === 1) {
					orders.value = newData; // 第一页替换列表
				} else {
					orders.value = [...orders.value, ...newData]; // 后续页面追加数据
				}
			
		        // 检查这是否是最后一页
				if (orders.value.length == totalNum.value) {
					finished.value = true;
		            loadingText.value = orders.value.length === 0 ? '暂无数据' : '没有更多数据了';
					console.log("已到达数据末尾。");
				} else {
		            // 如果未完成，为下一页做准备
		            pageNo.value++; // 为*下一次* loadMore 调用增加 page number
		        }
			
			} else {
				// 处理 API 错误或第一页的空数据
		        if (pageNo.value === 1) {
		            orders.value = []; // 如果第一页失败或未返回数据，则清空列表
		        }
				finished.value = true; // 如果出错或响应意外，则假定已完成
		        loadingText.value = orders.value.length === 0 ? '暂无数据' : '加载失败';
				uni.showToast({ title: res.msg || '加载失败', icon: 'none' });
				console.error("API 错误或无数据:", res.msg);
			}
		} catch (error) {
			console.error("获取订单列表时出错:", error);
		    if (pageNo.value === 1) {
		        orders.value = []; // 第一页出错时清空列表
		    }
			finished.value = true; // 在 catch 时假定已完成
		    loadingText.value = orders.value.length === 0 ? '暂无数据' : '加载出错';
			uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
		} finally {
			loading.value = false; // 重置 loading state
		    uni.stopPullDownRefresh(); // 停止下拉刷新指示器（如果激活）
		}
	}
	// 新增加载更多功能
	// 替换现有的占位 loadMore function
	const loadMore = () => {
	    console.log("滚动到达底部，尝试加载更多...");
		if (!loading.value && !finished.value) {
			// 调用 getShopList 表明这是一个 load more 操作
			getDeposit_orderListFun(true);
		} else {
	        console.log(`跳过 Load more：Loading=${loading.value}, Finished=${finished.value}`);
	    }
	};
	const depositRefund = (id) => {
		uni.showModal({
			title: '提示',
			content: '您确定要申请退款该押金吗？',
			success: function (res) {
				if (res.confirm) {
					console.log('用户点击确定');
					let obj = {
						order_id: id
					}
					payRefund_deposit(obj).then(res=>{
						console.log(res)
						if(res.code == 1){
							getDeposit_orderListFun(false)
						}
					}).catch(error=>{
						console.log(error)
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
		
	}
	const cancelOrderFun = (id) => {
		uni.showModal({
			title: '提示',
			content: '您确定要取消该押金吗？',
			success: function (res) {
				if (res.confirm) {
					console.log('用户点击确定');
					deposit_orderCancel({order_id: id}).then(res=>{
						console.log(res)
						if(res.code == 1){
							getDeposit_orderListFun(false)
						}
					}).catch(error=>{
						console.log(error)
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
		
	}
	const payOrder = (item) => {
		let payObj = {
			order_id: item.id
		}
		payDeposit(payObj).then(payRes=>{
			console.log(payRes)
			if(payRes.code == 1){
				uni.showLoading({
					title: '加载中……',
					mask: true
				})
				
				wx.config({
				  debug: false,
				  appId: payRes.data.appId,
				  timestamp: payRes.data.timeStamp || "",
				  nonceStr: payRes.data.nonceStr || "",
				  signature: payRes.data.paySign || "",
				  jsApiList: [
					'chooseWXPay',         // 微信支付
					'updateAppMessageShareData', // 分享到朋友圈
					'updateTimelineShareData',    // 分享给朋友
					'getLocation', // 获取位置
						  // 其他需要调用的API
				  ]
				});
				wx.ready(() => {
					uni.hideLoading()
					wx.chooseWXPay({
					  timestamp: payRes.data.timeStamp,
					  nonceStr: payRes.data.nonceStr,
					  package: payRes.data.package,
					  signType: payRes.data.signType,
					  paySign: payRes.data.paySign,
					  success: (WXPayres) => {
						  console.log('支付成功')
						  uni.showToast({
							title: `支付成功${JSON.stringify(WXPayres)}`,
							duration: 1000
						  })
					  },
					  fail: (WXPayerror) => {
						  uni.showToast({
							title: `支付失败${JSON.stringify(WXPayerror)}`,
							duration: 1000
						  })
					  }
					});
				});
			}
		}).catch(payError=>{
			console.log(payError)
		})
	}
	onLoad(()=>{
		getDeposit_orderListFun(false)
	})
	const tabChange = (index: number) => {
		console.log(index)
		tabIndex.value = index
		getDeposit_orderListFun(false)
	}
</script>

<style scoped>
	page {
		height: 100%;
		background-color: #f5f5f5;
	}

	.page {
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.order-status {
		height: 96rpx;
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		background-color: #ffffff;
		margin-bottom: 20rpx;
	}

	.status-item {
		position: relative;
		font-size: 28rpx;
		color: #666666;
		margin-right: 64rpx;
	}

	.status-item.active {
		color: #ff6634;
		font-weight: bold;
	}

	.dot {
		position: absolute;
		top: -16rpx;
		right: -16rpx;
		width: 8rpx;
		height: 8rpx;
		border-radius: 50%;
		background-color: #ff6634;
	}

	.order-list {
		flex: 1;

		overflow: auto;
		padding: 0 32rpx;
	}
	.none{
		/* width: 100rpx;
		height: 100rpx; */
		font-size: 24rpx;
		color: #999999;
	}
	.order-card {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 32rpx;
		width: 686rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.hotel-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}

	.order-state {
		font-size: 28rpx;
		color: #ff6634;
	}

	.card-info {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.room-price-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.room-info {
		display: flex;
		align-items: center;
	}

	.info-text {
		font-size: 28rpx;
		color: #999999;
		margin-left: 8rpx;
	}

	.price {
		display: flex;
		align-items: baseline;
	}

	.currency {
		font-size: 32rpx;
		color: #ff6634;
	}

	.amount {
		font-size: 48rpx;
		color: #ff6634;
		font-weight: bold;
	}

	.divider {
		height: 2rpx;
		background-color: #eeeeee;
		margin: 24rpx 0;
	}

	.card-actions {
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;
	}

	.btn-cancel {
		width: 200rpx;
		height: 68rpx;
		line-height: 68rpx;
		border: 2rpx solid #dddddd;
		border-radius: 48rpx;
		font-size: 26rpx;
		color: #666666;
		background-color: #ffffff;
	}

	.btn-pay {
		width: 200rpx;
		height: 68rpx;
		line-height: 68rpx;
		border-radius: 48rpx;
		font-size: 28rpx;
		color: #ffffff;
		background-color: #ff6634;
	}

	.tab-bar {
		height: 112rpx;
		display: flex;
		align-items: center;
		background-color: #ffffff;
		padding: 12rpx 0;
		flex-shrink: 0;
	}

	.tab-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.tab-item text {
		font-size: 20rpx;
		color: #999999;
		margin-top: 8rpx;
	}

	.tab-item.active text {
		color: #ff6634;
	}

	.cursor-pointer {
		cursor: pointer;
	}
</style>